import {
  ClassGetPage,
  ClassSave,
  ClassDelete,
  ClassUpdate
} from "@/api/teacher/zsclass";
import { GetAllOrganization } from "@/api/admin/teacher";
import qs from "qs";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import dayjs from "dayjs";
import { ZeroFill } from "@/utils/public/method";

export function useClass() {
  const form = reactive({
    ClassName: "",
    remark: ""
  });

  const updateClassDto = reactive({
    ClassId: "",
    ClassNO: "",
    ClassName: "",
    UserNum: 0,
    ExpirationTime: "",
    // OrganizationId: "",
    OrganizationName: "",
    Remark: "",
    SortNo: 0
  });

  const dataList = ref([]);
  const loading = ref(false);
  const updatePanelVisible = ref(false);
  const loadingTitle = ref("修改");
  const ruleForm = ref({});
  const MGetAllOption = ref();

  const usersNumber = (rule: any, value: any, callback: any) => {
    if (value === "" || value == 0) {
      callback(new Error("请输入用户数量"));
    } else if (Number(value) < 0) {
      callback(new Error("用户数量不能为负数"));
      updateClassDto.UserNum = 0;
    } else if (Number(value) > 9999) {
      callback(new Error("用户数量最值为9999"));
      updateClassDto.UserNum = 9999;
    } else {
      callback();
    }
  };
  const rules = {
    ClassNO: [
      {
        required: true,
        message: "请输入班级编号！",
        trigger: ["blur", "change"]
      }
    ],
    ClassName: [
      {
        required: true,
        message: "请输入班级名称！",
        trigger: ["blur", "change"]
      }
    ],
    // OrganizationId: [
    //   {
    //     required: true,
    //     message: "请选择机构组织",
    //     trigger: "blur"
    //   }
    // ],
    UserNum: [
      {
        required: true,
        validator: usersNumber,
        trigger: "blur"
      }
    ],
    ExpirationTime: [
      {
        required: true,
        message: "前选择过期时间",
        trigger: ["blur", "change"]
      }
    ]
  };

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    // pageSizes: [10, 20, 50, 100],
    background: true
  });

  const columns: TableColumnList = [
    {
      label: "序号",
      minWidth: 30,
      type: "index"
    },
    {
      label: "班级编号",
      prop: "classNO",
      minWidth: 100
    },
    {
      label: "班级名称",
      prop: "className",
      minWidth: 100
    },
    {
      label: "机构组织",
      prop: "organizaName",
      minWidth: 100
    },
    {
      label: "用户数量",
      prop: "userNum",
      minWidth: 50
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 80,
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "到期时间",
      prop: "expirationTime",
      minWidth: 100,
      formatter: ({ expirationTime }) =>
        dayjs(expirationTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "备注",
      prop: "remark",
      minWidth: 100
    },

    {
      label: "操作",
      fixed: "right",
      width: 150,
      slot: "operation"
    }
  ];

  function updateNumber(rForm) {
    ruleForm.value = rForm;
  }
  async function handleDelete(row) {
    ElMessageBox({
      title: '提示', //MessageBox 标题
      closeOnClickModal: false,
      message: '是否确定删除当前项?', //MessageBox 消息正文内容
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const classId = qs.stringify({ classId: row.classId });
      const res = await ClassDelete(classId);
      if (res.success) {
        ElMessage({
          message: "删除成功",
          type: "success"
        });
        onSearch();
      } else {
        ElMessage({
          message: res.msg,
          type: "error"
        });
      }
      // 确定
    }).catch(() => { })
    // const classId = qs.stringify({ classId: row.classId });
    // const res = await ClassDelete(classId);
    // if (res.success) {
    //   ElMessage({
    //     message: "删除成功",
    //     type: "success"
    //   });
    //   onSearch();
    // } else {
    //   ElMessage({
    //     message: res.msg,
    //     type: "error"
    //   });
    // }
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await ClassGetPage({
      pageindex: pagination.currentPage,
      pagesize: pagination.pageSize,
      ...form
    });
    dataList.value = data.list;
    pagination.total = data.totalCount;
    loading.value = false;
  }



  // 添加班级or修改班级
  async function updateClass(row: any | undefined) {
    updatePanelVisible.value = true;
    console.log("row", row)
    // console.log("updateClass", row)
    if (row) {
      loadingTitle.value = "修改";
      nextTick(() => {
        updateClassDto.ClassId = row.classId;
        updateClassDto.UserNum = row.userNum;
        updateClassDto.ClassNO = row.classNO;
        updateClassDto.ClassName = row.className;
        updateClassDto.ExpirationTime = row.expirationTime;
        // updateClassDto.OrganizationId = row.organizaName;
        updateClassDto.OrganizationName = row.organizationId;
        updateClassDto.Remark = row.remark;
      });
    } else {
      updateClassDto.SortNo = 0;
      updateClassDto.ClassId = "";
      updateClassDto.ClassNO = "";
      // updateClassDto.ClassNO = ZeroFill(classId.data.toString(), 4);
      loadingTitle.value = "添加";
    }
  }

  // 保存
  const addClass = (ClassToRef: FormInstance | undefined) => {
    if (!ClassToRef) return;
    (ClassToRef as any).validate(async valid => {
      if (valid) {
        const data = {
          classId: updateClassDto.ClassId,
          userNum: updateClassDto.UserNum,
          classNO: updateClassDto.ClassNO,
          className: updateClassDto.ClassName,
          expirationTime: updateClassDto.ExpirationTime,
          // organizationId: updateClassDto.OrganizationId.organizationId || updateClassDto.OrganizationName,
          remark: updateClassDto.Remark,
        };
        let respone = null;
        if (updateClassDto.ClassId == '') {
          respone = await ClassSave(data);
        } else {
          respone = await ClassUpdate(data);
        }
        if (respone.success) {
          ElMessage({
            message: respone.msg,
            type: "success"
          });
          ClosePanelVisible(ClassToRef);
          onSearch();
        } else {
          ElMessage({
            message: respone.msg,
            type: "error"
          });
        }
      }
    });
  };

  // 关闭
  function ClosePanelVisible(row: FormInstance | undefined) {
    if (!row) return;
    updatePanelVisible.value = false;
    updateClassDto.OrganizationName = ""
    row.resetFields();
  }

  // 获取机构组织
  async function GetAllOption() {
    const respone = await GetAllOrganization();
    if (respone.success) {
      MGetAllOption.value = respone.data
    } else {
      ElMessage.error(respone.msg);
    }
  }

  onMounted(() => {
    onSearch();
    GetAllOption()
  });
  return {
    form,
    rules,
    loading,
    columns,
    dataList,
    loadingTitle,
    pagination,
    updateClassDto,
    MGetAllOption,
    updatePanelVisible,
    onSearch,
    updateNumber,
    updateClass,
    handleDelete,
    ClosePanelVisible,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    addClass
  };
}
